package logic

import (
	"context"
	"fmt"
	"zhihu/models"
	"zhihu/pkg"

	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FindPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFindPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindPasswordLogic {
	return &FindPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FindPasswordLogic) FindPassword(in *zhihu_rpc.FindPasswordRequest) (*zhihu_rpc.FindPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在")
	}
	if user.UserPhone != in.Phone {
		return nil, fmt.Errorf("输入的手机号与账号绑定不匹配")
	}
	key := fmt.Sprintf("%s:phone:%s", "find_password", in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if in.Code != get {
		return nil, fmt.Errorf("验证码错误")
	}
	user.UserPassword = pkg.MD5(in.Password)
	if models.DB.Where("id = ?", user.ID).Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &zhihu_rpc.FindPasswordResponse{}, nil
}
